<template>
  <div class="app-container">
     <!-- 标题 -->
   	<header class="app-header">
    	<span class="title">{{$route.meta.title}}</span>
      <div class="back" @click="goBack">
        <i class="el-icon-back" ></i>
        <el-divider direction="vertical"></el-divider>
        <el-button type="text">返回</el-button>
      </div>
    </header> 
    <el-container  style="padding:0">
      <el-aside class="classify" width="300px">
  			<div class="tit-path">
        	频道配置
          <el-button-group class="tit-btn">
          	<el-button type="primary" icon="el-icon-document-add" size="mini" @click.native="addChannelCate">添加</el-button>
          	<el-button :type="changeSetIng ? 'success':'danger'" @click="changeSetIngFn" :icon="changeSetIng ? 'el-icon-open':'el-icon-turn-off'" size="mini">设置</el-button>
        	</el-button-group>
        </div> 
       
        <el-tree  :data="treeList" ref="channelTree" node-key="id" :current-node-key="selectTreeKey" :draggable="isDraggable" @node-drag-end="handleDragEnd" :allow-drop="allowDrop" style="user-select:none" :highlight-current="true" :expand-on-click-node="false" default-expand-all>	
            <div class="tree-path" slot-scope="{ node, data }"  @click="loadDate(data)">
              <span v-show="!data.extend" class="tree-title">{{  data.name }}</span>
              <span v-show="data.extend" class="tree-title">
                <el-input style="width:100%;"  placeholder="输入英文名称" size="mini" v-model.trim="data.name" auto-complete="off"></el-input>
              </span>
              <el-button-group class="tit-btn" v-if="changeSetIng">
              	<el-button v-show="!data.extend" type="primary" size="mini" icon="el-icon-edit" @click.stop="() => changeState(data)"></el-button>
                <el-button v-show="data.extend" type="warning" size="mini" icon="el-icon-document-checked" @click.stop="() => updateList(data)"></el-button>
                <el-button v-if="data.parentId == '0'" :disabled="data.extend" type="primary" size="mini" icon="el-icon-document-add" @click.stop="() => appendChild(data)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click.stop="() => remove(node, data)"></el-button>
             </el-button-group>
            </div>
        </el-tree>
      </el-aside>
      <el-main style=" padding:0 15px;">
      <template v-if="curItem.type == 0">
      	<el-form :inline="true" :model="listQueryRes" class="query-form">
        	 <el-form-item>	
            <el-select v-model="curItem.type" @change="changeCurItem" placeholder="请选择状态">
              <el-option label="资源" :value="0" />
              <el-option label="资讯" :value="1" />
            </el-select>             
          </el-form-item>
           <el-form-item class="query-form-item">
           		<el-input v-model="listQueryRes.resName" :clearable = "true" placeholder="请输入资源名称"></el-input>
           </el-form-item>
           <el-form-item>
           		<el-button-group>
           		  <el-button type="primary" icon="el-icon-search"  @click="onSubmit">查询</el-button>
           		  <el-button type="primary" icon="el-icon-edit"  @click="onAddRes">关联</el-button>	
           		</el-button-group>
           </el-form-item>
        </el-form>
        
        <el-table ref="multipleTable" key="1" v-loading="loading" row-key="id" :data="listRes" :row-class-name="selectRowClass" border  @selection-change="handleSelectionChange">
        	<el-table-column align="center" width="70" type="selection"  :reserve-selection="true"></el-table-column>
          
          <el-table-column align="center" label="资源名称" prop="resName" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="缩略图" width="120">
          	<template slot-scope="scope">
            	<div class="view-img-x">
            		<img  :src="scope.row.resUrl | setResUrl(scope.row.resType)" />
            	</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="类型" prop="resType"  width="100">
            <template slot-scope="scope">
              <template>{{ scope.row.resType | typeFilter }}</template>
            </template>
          </el-table-column>          
        	<el-table-column align="center" label="大小" prop="resSize" width="100">
            <template slot-scope="scope">
              {{ scope.row.resSize?scope.row.resSize:'---' }}
            </template>          
          </el-table-column>
          <el-table-column align="center" label="上传时间" prop="created"  show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.created | parseTime('{y}-{m}-{d} {h}:{i}') }}
            </template>        
          </el-table-column>       
        </el-table>
        <pagination v-show="totalRes > listQueryRes.pageSize" :total="totalRes" :page.sync="listQueryRes.page" :limit.sync="listQueryRes.pageSize" @pagination="getResList"/>
      </template>

      <template v-if="curItem.type == 1">  
      	<el-form :inline="true" :model="listQueryContent" class="query-form">
        	<el-form-item>	
            <el-select v-model="curItem.type" @change="changeCurItem" placeholder="请选择状态">
              <el-option label="资源" :value="0" />
              <el-option label="资讯" :value="1" />
            </el-select>             
          </el-form-item> 
          <el-form-item>
            <el-input v-model="listQueryContent.title" :clearable = "true" placeholder="请输入标题"></el-input>
          </el-form-item>          
          <el-form-item>
            <el-button-group>
             <el-button type="primary" icon="el-icon-search"  @click="onSubmit">查询</el-button>
             <el-button type="primary" icon="el-icon-edit"  @click="onAddContent">关联</el-button>	
            </el-button-group>
          </el-form-item>          	
        </el-form>  
				<el-table  ref="multipleTable" key="2"  v-loading="loading" row-key="id" :row-class-name="selectRowClass" :data="listContent" border  @selection-change="handleSelectionChange">
  			 	<el-table-column align="center" width="70" type="selection"  :reserve-selection="true" ></el-table-column>
          <el-table-column align="center" label="标题" prop="title"></el-table-column>
          <el-table-column align="center" label="点赞数" prop="likeNum" width="80" />
      		<el-table-column align="center" label="点击数" prop="clickNum" width="80" />
      		<el-table-column align="center" label="修改时间" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.updateDate | parseTime('{y}-{m}-{d} {h}:{i}') }}
            </template>        
          </el-table-column>            
       	</el-table>
        <pagination v-show="totalContent > listQueryContent.pageSize" :total="totalContent" :page.sync="listQueryContent.page" :limit.sync="listQueryContent.pageSize" @pagination="getContentList"/>
      </template>  
      </el-main>   	
		</el-container>    
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import request from '@/utils/request'
import config from '@/api/bgapi'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  components: { Pagination,ElImageViewer},	
  data() {
    return {
			treeList:[],
			formLoading:false,
			formData:{
				name:'',type:0,resData:[],contentData:[]
			},
			changeSetIng:false,
			formRules:{},
			curItem:{type:1},
			listQueryRes:{page:1,pageSize:20},
			listRes:[],
			loading:false,
			totalRes:0,
			listQueryContent:{page:1,pageSize:10,title:''},
			cateProps:{children: 'children', label: 'cateName' ,value:'id'},
			categories:[],
			listContent:[],
			totalContent:0,
			isDraggable:false,
			selectTreeKey:0,
		}
  },
  mounted(){
		this.id = this.$route.query.id;
		this.addId = 0;		
		this.selectItme = [];
		this.getList();
		//this.getResList();
		//this.getCategories();
		//this.getContentList();		
  },
  methods: {
		selectRowClass({row, rowIndex}) {
			if(row.sort > -1){
				return 'item';	
			}else{
				return '';	
			}
		},
		async getList(){
			var res = await request.get(config.getChannelCate,{params:{channelId:this.id}});
			if(res.data.length > 0){
				this.loadDate(res.data[0]);
				this.$nextTick(() => {
					this.$refs.channelTree.setCurrentKey(res.data[0].id)
				})
			}
			this.treeList = res.data;	
		},		
		async getCategories(){
			let res = await request.get(config.contentCate);
      if(res.code == '20000'){
        this.categories = res.data;
      }					
		},
		async getResList(){
			this.listQueryRes.channelCateId = this.curItem.channelCateId;
			var res = await request.get(config.getChannelRes,{params:this.listQueryRes});
			this.listRes = res.data || [];
			this.$nextTick(() => {
				this.$refs.multipleTable.clearSelection();
				this.listRes.forEach(item =>{
					if(item.sort != null && item.sort > -1){
						this.$refs.multipleTable.toggleRowSelection(item,true);
					}
				})
				const el = this.$refs.multipleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
				this.sortable = Sortable.create(el, {
					draggable: ".item",
					ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
					setData: function(dataTransfer) {
						dataTransfer.setData('Text', '')
					},					
					onEnd: async (evt) => {									
						const targetRow = this.selectItme.splice(evt.oldIndex, 1)[0];
						this.selectItme.splice(evt.newIndex, 0, targetRow);	
						let ids = this.selectItme.map((item,index) =>{ return item.id});
						await request.put(config.setChannelCate+'/'+this.curItem.channelCateId,{type:0,resData:ids});
					}
				})		
			})
			this.totalRes = res.totalNum || 0;
		},				
		async getContentList(){
			this.listQueryContent.channelCateId = this.curItem.channelCateId
			var res = await request.get(config.getChannelContent,{ params:this.listQueryContent } );
			this.listContent = res.data || [];
			this.$nextTick(() => {
				this.listContent.forEach(item =>{
					if(item.sort != null && item.sort > -1){
					 this.$refs.multipleTable.toggleRowSelection(item,true);	
					}
				})	
				const el = this.$refs.multipleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
				this.sortable = Sortable.create(el, {
					draggable: ".item",
					ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
					setData: function(dataTransfer) {
						dataTransfer.setData('Text', '')
					},					
					onEnd: async (evt) => {				
						const targetRow = this.selectItme.splice(evt.oldIndex, 1)[0]
						this.selectItme.splice(evt.newIndex, 0, targetRow);	
						await request.put(config.setChannelCate+'/'+this.curItem.channelCateId,{type:1,contentData:this.selectItme});
					}
				})				
			})			
			this.totalContent = res.totalNum || 0;		 
		},		
		changeSetIngFn(isChange){
			if(isChange === true){
				this.changeSetIng = true;
			}else{
				this.changeSetIng = !this.changeSetIng;
			}
			this.listContent = [];
			this.listRes = [];
			if(!this.changeSetIng){
				this.getList();	
				this.isDraggable = false;
			}else{
				this.isDraggable = true;
			}
		},		
		addChannelCate(){
			this.changeSetIngFn(true);
			this.addId++;			
			let _data = {channelId:this.id, id:this.addId, name:'', type:0,  parentId:'0',extend:true};
			this.treeList.push(_data);		
		},		
		changeState(data){
			if(data.id){data.extend	 = true}			
		},		
		async appendChild(data){
			this.addId++;			
			var newChild = {parentId:data.id, id:this.addId, type:0, name:'',channelId:this.id, extend:true};
	    if (!data.children) {
        this.$set(data, 'children', []);
      }	
			data.children.push(newChild);
		},		
		async updateList(data) {
			if(!data.name){this.$message.error('请输入英文分类名称！');return;}
			if(data.id && typeof(data.id) == 'string'){
				/*update*/
				var res = await request.put(config.setChannelCate+'/'+data.id,{name:data.name});
				if(res.code == '20000'){
					data.extend	 = false;
				}				
			}else{
				/*add*/
				var newChild = {
					name:data.name,type:0,parentId:data.parentId,channelId:this.id
				};	
				var res = await request.post(config.addChannelCate,newChild);
				if(res.code == '20000'){
					this.$set(data, 'extend', false);
					this.$set(data, 'id', res.data.id);
					this.$set(data, 'orderNo', res.data.orderNo);						
				}
			}
		},
		async remove(node, data) {
			if(typeof(data.id) == 'string'){
				var res = await request.delete(config.delChannelCate+'/'+data.id);
				this.getList();
			}else{
				const parent = node.parent;
				const children = parent.data.children || parent.data;
				const index = children.findIndex(d => d.id === data.id);
				children.splice(index, 1);
			}
		},	
		loadDate(data){
			if(this.changeSetIng){ return }
			this.$refs.multipleTable.clearSelection();
			this.curItem.type = data.type;
			this.curItem.channelCateId = data.id;
			if(this.curItem.type == '0'){
				this.getResList()
			}else if(this.curItem.type == '1'){
				this.getContentList()	
			}	
		},		
		allowDrop(draggingNode, dropNode, type) {
			if (draggingNode.level === dropNode.level) {
				if (draggingNode.parent.id === dropNode.parent.id) {
					return type === "prev" || type === "next";
				}
			} else {
				return false;
			}
		},
		async handleDragEnd(draggingNode, dropNode, dropType, ev) {
			if(draggingNode.key != dropNode.key){
				var _draggingNodeId = draggingNode.data.id;
				var _draggingNodeOrderNo = draggingNode.data.orderNo;
				var _dropNodeId = dropNode.data.id;
				var _dropNodeOrderNo = dropNode.data.orderNo;
				this.isDraggable = false;
				await request.put(config.setChannelCate+'/'+_draggingNodeId,{orderNo:_dropNodeOrderNo});
				await request.put(config.setChannelCate+'/'+_dropNodeId,{orderNo:_draggingNodeOrderNo});	
				this.getList();
				this.isDraggable = true;
			}
		},
		handleSelectionChange(val){
			//this.selectItme = val.map((item,index) =>{ return item.id});
			this.selectItme = val;
		},
		async onAddRes(){
			if(!this.curItem.channelCateId){return}
			let ids = [];
			this.selectItme.forEach( item => {
				if(item.resType == 10){
					ids.push(...item.resIds)
				}else{	
					ids.push(item.id)
				}
			})
			var res = await request.put(config.setChannelCate+'/'+this.curItem.channelCateId,{type:0,resData:ids})
			if(res.code == '20000'){
				this.$message.success('资源操作成功！')
				this.listQueryRes.page = 1;
				this.getResList();
			}
		},
		async onAddContent(){
			if(!this.curItem.channelCateId){return}
 			var res = await request.put(config.setChannelCate+'/'+this.curItem.channelCateId,{type:1, contentData:this.selectItme})
			if(res.code == '20000'){
				this.$message.success('资讯操作成功！')
				this.listQueryContent.page = 1;
				this.getContentList();
			}
		},	
		changeCurItem(){
			this.$refs.multipleTable.clearSelection();
			if(this.curItem.type == '0'){
				this.getResList()
			}else if(this.curItem.type == '1'){
				this.getContentList()	
			}	
		},
		goBack(){
			this.$router.back();
		},		
		onSubmit(){
			if(this.curItem.type == '0'){
				this.getResList()
			}else if(this.curItem.type == '1'){
				this.getContentList()	
			}
		},
		async formSubmit(){
			this.formLoading = false;
			this.formData.channelId = this.id;
			var res = await request.post(config.addChannelCate,this.formData);
			this.formLoading = true;
			this.getList();
		}
	},
  filters: {
    typeFilter(status) {
      const typeMap = { 0: '图片', 1: '视频', 2: '音频', 3: '文字',9:'富文本',10:'组合' }
      return typeMap[status]
    },
		setResUrl(img,type){
			if(type == '0'){
				return process.env.VUE_APP_BASE_API+img;	
			}else if(type == '1'){
				return require('@/assets/images/video.png');	
			}else if(type == '2'){
				return require('@/assets/images/audio.png');	
			}else if(type == '3'){
				return require('@/assets/images/text.png');
			}else if(type == '9'){
				return require('@/assets/images/edit-text.png');
			}else if(type == '10'){
				return require('@/assets/images/group.png');
			}
		},		
		parseCate(cateIds,cateArr){
			var arr = cateIds;
			var data = cateArr;
			function getCity(arr, data, city = []) {
				if (typeof data === "object") {
						for (let i = 0; arr[i] !== undefined; i++) {
								for (let j = 0; data[j] !== undefined; j++) {
										if (arr[i] === data[j].id) {
												city.push(data[j].cateName);
										}
								}
						};
						for (let i = 0; data[i] !== undefined; i++) {
								getCity(arr, data[i].children, city);
						};
				}
				return city;
			}

			var str = getCity(arr,data).join('/')
			
			return str;
		}		
  },  
}
</script>
<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #1890FF!important;
}
</style>
<style scoped>
.tit-path{ padding:0 0 0 8px;  margin:0px 0 20px; font-size:16px; }
.tit-btn{ float:right; border-radius:25px; margin-top:3px;}
.tit-btn >>> button.el-button{height:25px; line-height:25px; padding:0 8px;}

.tree-path{flex: 1; display: flex; align-items: center; font-size:14px; justify-content: space-between;}
.custom-tree-node { height:50px; padding:0; margin:0; vertical-align:middle; border:1px solid blue;}	
.classify { background:#FAFAFA; padding:10px}
.classify >>> .el-tree-node__content{height: 40px; line-height: 40px; padding-right:10px;}
.tree-title >>> .el-input__inner{ padding-left:5px; margin-left:-5px;}
.view-img-x{ vertical-align:middle; line-height:0;border:0px solid #FAFAFA;  height:40px; margin:0 0 0 10px; line-height:0; width:auto; max-width:80px;}
.view-img-x >>> img{ max-width:100% !important; max-height:100%  !important;}
</style>